package com.opendeepsearch.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class ArxivSearchTool implements Tool {
    private static final Logger logger = LoggerFactory.getLogger(ArxivSearchTool.class);
    private static final String ARXIV_API_URL = "http://export.arxiv.org/api/query";

    @Override
    public String getName() {
        return "arxiv_search";
    }

    @Override
    public String getDescription() {
        return "在ArXiv上搜索学术论文";
    }

    @Override
    public String execute(String input) throws IOException, InterruptedException {
        if (input == null || input.trim().isEmpty()) {
            throw new IllegalArgumentException("Search input cannot be null or empty");
        }
        
        String query = input.trim();
        logger.debug("Searching ArXiv for: {}", query);
        
        try {
            String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);
            String apiUrl = String.format("%s?search_query=all:%s&start=0&max_results=10", ARXIV_API_URL, encodedQuery);
            
            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(10))
                    .build();

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(apiUrl))
                    .timeout(Duration.ofSeconds(15))
                    .header("Accept", "application/atom+xml")
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            
            if (response.statusCode() == HttpURLConnection.HTTP_OK) {
                return response.body();
            } else {
                String errorMsg = "ArXiv search failed: " + response.statusCode() + " - " + response.body();
                logger.error(errorMsg);
                throw new IOException(errorMsg);
            }
        } catch (Exception e) {
            logger.error("Error during ArXiv search", e);
            throw new IOException("Failed to search ArXiv", e);
        }
    }
}
